<template>
    <el-form label-width="120px" :model="skuInfo" :rules="rules" ref="formRef">
        <el-form-item label="SPU名称">
            <span>{{ props.currentSpu.spuName }}</span>
        </el-form-item>
        <el-form-item label="SKU名称" prop="skuName">
            <el-input placeholder="SKU名称" v-model="skuInfo.skuName" />
        </el-form-item>
        <el-form-item label="价格(元)" prop="price">
            <el-input type="number" placeholder="0" v-model="skuInfo.price" />
        </el-form-item>
        <el-form-item label="重量(千克)" prop="weight">
            <el-input type="number" placeholder="0" v-model="skuInfo.weight" />
        </el-form-item>
        <el-form-item label="规格描述" prop="skuDesc">
            <el-input placeholder="规格描述" type="textarea" :rows="4" v-model="skuInfo.skuDesc" />
        </el-form-item>
        <el-form-item label="平台属性" prop="skuAttrValueList">
            <el-form label-width="80px" inline>
                <el-form-item v-for="(item, index) in attrList" :label="item.attrName" :key="item.id"
                    style="margin-bottom:10px">
                    <el-select v-model="skuAttrValueList[index]" @change="clearAttrRules" class="m-2" placeholder="请选择">
                        <el-option v-for="value in item.attrValueList" :key="value.id" :label="value.valueName"
                            :value="`${value.id}:${value.attrName}:${value.id}:${value.valueName}`" />
                    </el-select>
                </el-form-item>
            </el-form>
        </el-form-item>
        <el-form-item label="销售属性" prop="skuSaleAttrValueList">
            <!-- <el-row :gutter="20" > -->
            <el-form label-width="80px" inline>
                <el-form-item :label="item.saleAttrName" v-for="(item, index) in spuSaleAttrList" :key="item.id"
                    style="margin-bottom:10px">
                    <el-select class="m-2" v-model="skuSaleAttrValueList[index]" @blur="clearAttrValueRules"
                        placeholder="请选择">
                        <el-option v-for="value in item.spuSaleAttrValueList" :value="
                        `${value.id}:${value.saleAttrName}:${value.id}:${value.saleAttrValueName}`" :key="value.id"
                            :label="value.saleAttrValueName" />
                    </el-select>
                </el-form-item>

            </el-form>

        </el-form-item>
        <el-form-item label="图片列表">
            <el-table border :data=spuImageList>
                <el-table-column type="selection" width="55" />
                <el-table-column label="图片">
                    <template v-slot="{ row }">
                        <img :src="row.imgUrl" style="height:80px">
                    </template>
                </el-table-column>
                <el-table-column label="名称" prop="imgName" />
                <el-table-column label="操作">
                    <template v-slot="{ row }">
                        <el-button type="primary" v-if="row.isDefault == '0'" @click="setDefault(row)">设置默认
                        </el-button>
                        <el-tag type="success" v-else>默认</el-tag>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="preservation(formRef)">保存</el-button>
            <el-button @click="emits('setShowStatus', 1)">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts">
export default {
    name: 'SkuForm'
}
</script>

<script lang="ts" setup>
import type { FormRules, FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { ref, reactive, onMounted } from 'vue'
import { reqGetAttrListData } from '@/api/product/attr'
import { getSpuSaleAttrListApi, reqGetSpuImageList } from '@/api/product/spu'
import { reqSaveSkuInfo } from '@/api/product/sku'
import { useGetCategoryStore } from '@/stores/categoryList'
import type { skuInfoModel, } from '@/api/product/model/skuModel'
import type { SpuSaleAttrListModel } from '@/api/product/model/spu'
const categoryStore = useGetCategoryStore()
// 定义事件
const emits = defineEmits(['setShowStatus']);
const props = defineProps(['currentSpu'])
const formRef = ref<FormInstance>()
const skuAttrValueList = ref<string[]>([])
const skuSaleAttrValueList = ref<string[]>([])

// 生成初始化skuInfo数据
const skuInfo = reactive<skuInfoModel>({
    skuName: '',
    price: 0,
    weight: 0,
    skuDesc: '',
    // 平台属性
    skuAttrValueList: [
        // {
        //   attrId: 0,
        //   attrName: 'string',
        //   valueId: 0,
        //   valueName: 'string',
        // },
    ],
    skuSaleAttrValueList: [
        // {
        //   saleAttrId: 0,
        //   saleAttrName: 'string',
        //   saleAttrValueId: 0,
        //   saleAttrValueName: 'string',
        //   spuId: 0,
        // },
    ],
    // 默认图片
    skuDefaultImg: '',
    skuImageList: [
        // {
        //   imgName: 'string',
        //   imgUrl: 'string',
        //   isDefault: 'string',
        //   spuImgId: 0,
        //   isDefault: "1"
        // },
    ],

})

// 书写校验规则
const skuImageListValidate = (rule: any, value: any, callback: any) => {
    if (value.length === 0) {
        callback('请至少选择一张图片……')
        return
    }
    if (!value.find((item: any) => item.isDefault === '1')) {
        callback('请选择一张默认图片……')
        return
    }
    callback()
}
const rules = reactive<FormRules>({
    skuName: [
        { required: true, message: '请输入sku名称', trigger: 'blur' },
        { min: 1, max: 10, message: '长度在1到10之间', trigger: 'blur' }
    ],
    price: [{ required: true, message: '请输入sku价格', trigger: 'blur' }],
    weight: [{ required: true, message: '请输入sku重量', trigger: 'blur' }],
    skuDesc: [{ required: true, message: '请输入sku描述', trigger: 'blur' }],
    skuAttrValueList: [
        { required: true, message: '请至少选择一个平台属性', type: 'array', trigger: 'change' }
    ],
    skuSaleAttrValueList: [
        { required: true, message: '请至少选择一个销售属性', type: 'array', trigger: 'change' }
    ],
    skuImageList: [
        { required: true, validator: skuImageListValidate, trigger: 'change' }
    ]
})


const spuImageList = ref([]) // 用于显示的图片列表
const spuSaleAttrList = ref<SpuSaleAttrListModel>([])
const attrList = ref([])
onMounted(async () => {
    const result = await reqGetAttrListData({
        category1Id: categoryStore.category1Id,
        category2Id: categoryStore.category2Id,
        category3Id: categoryStore.category3Id
    })
    // console.log('xxx', result);
    attrList.value = result
})
onMounted(async () => {
    spuSaleAttrList.value = await getSpuSaleAttrListApi(props.currentSpu.id)

})
onMounted(async () => {
    let result = await reqGetSpuImageList(props.currentSpu.id)
    spuImageList.value = result.map((item: any) => {
        return {
            ...item,
            isDefault: '0'
        }
    })
    // console.log('图片', spuImageList.value);

})


// 设置为默认值
const setDefault = (row: any) => {
    spuImageList.value.map(item => {
        item.isDefault = '0'
        return item
    })
    row.isDefault = '1'
    skuInfo.skuDefaultImg = row.imgUrl
}

// 清除平台属性的校验
const clearAttrRules = () => {
    formRef.value?.clearValidate(['skuAttrValueList'])
}
// 清除销售属性的校验
const clearAttrValueRules = () => {
    formRef.value?.clearValidate(['skuSaleAttrValueList'])
}

// 保存
const preservation = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    // 这里校验的是skuInfo，所以数组里面必须有值，不能将push操作写在校验通过之后
    // 裁剪获取平台属性的数据
    skuInfo.skuAttrValueList = skuAttrValueList.value.filter(Boolean).map((item: any) => {
        const [attrId, attrName, valueId, valueName] = item.split(':')
        return {
            attrId,
            attrName,
            valueId,
            valueName
        }
    })
    skuInfo.skuSaleAttrValueList = skuSaleAttrValueList.value.filter(Boolean).map((item: any) => {
        const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = item.split(':')
        return {
            saleAttrId,
            saleAttrName,
            saleAttrValueId,
            saleAttrValueName
        }
    })

    await formEl.validate(async (valid, fields) => {
        if (valid) {
            skuInfo.spuId = props.currentSpu.id
            skuInfo.category3Id = props.currentSpu.category3Id

            await reqSaveSkuInfo(skuInfo)

            ElMessage.success('Sku添加成功……')
            emits('setShowStatus', 1)
        } else {
            console.log('提交失败');

        }
    })
}
</script>

<style>
</style>